package com.neuedu.it.newidea.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.it.newidea.po.User;
import com.neuedu.it.newidea.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 管理员账号初始化器
 * 在应用启动时自动创建管理员账号（如果不存在）
 */
@Component
@Order(1)
public class AdminUserInitializer implements CommandLineRunner {
    @Autowired
    private UserService userService;

    @Value("${admin.score}")
    private int adminScore;
    @Value("${admin.username}")
    private String adminUserName;
    @Value("${admin.password}")
    private String adminPassword;
    @Value("${admin.email}")
    private String adminEmail;


    
    @Override
    public void run(String... args) throws Exception {

        Optional<User> existingAdmin = Optional.ofNullable(userService.getOne(new QueryWrapper<User>().eq("u_score", adminScore)));

        if (existingAdmin.isPresent()) {
            System.out.println("管理员账号已存在，无需初始化");
            return;
        }
        try {
                User user = new User();
                user.setNickName(adminUserName);
                user.setLoginName(adminUserName);
                user.setLoginPwd(adminPassword);
                user.setEmail(adminEmail);
                user.setScore(adminScore);
                userService.save(user);
                System.out.println("管理员账号初始化成功");
        }catch (Exception e) {
                System.out.println("管理员账号初始化失败");
                e.printStackTrace();
        }

    }
}
